// $Id: loggerdotnetwork.cpp 64 2004-10-25 07:56:18Z hansemil $
#include "loggerdotnetwork.h"
#include "node.h"
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;

/**
 * @todo Write documentation
 */
void LoggerDotNetwork::eos_simulate_start(void *eos)
{
	fstream fout;
	openFile(&fout, "networktopology.start.dot");
	outputNetoworkDot((Eos *) eos, fout);
	fout.close();
}

/**
 * @todo Write documentation
 */
void LoggerDotNetwork::eos_simulate_stop(void *eos)
{
	fstream fout;
	openFile(&fout, "networktopology.end.dot");
	outputNetoworkDot((Eos *) eos, fout);
	fout.close();
}

/**
 * Writes the dot-files to disk
 * @param eos Pointer to the simulator where we will get the node list
 * @param outputFile The fstream that the data should be written to.
 */
void LoggerDotNetwork::outputNetoworkDot(Eos *eos, fstream &outputFile)
{
	std::list<Node *> *nodes;
	std::list<RoutingEntry> *neighbors, *neighborneighbors;

	// Write dot header
	outputFile << "graph G {" << endl;

	// Write dot data
	nodes = eos->getNodes();
	for (std::list<Node *>::iterator node=nodes->begin(); node!=nodes->end(); node++) {
		neighbors = (*node)->getNeighbors();
		for (std::list<RoutingEntry>::iterator neighbor=neighbors->begin(); neighbor!=neighbors->end(); neighbor++) {
			outputFile << "n" << (*node) << " -- " << "n" << (*neighbor).m_node << " [dir=";

			// Find if the neighbor has a backlink and log it (unefficient way...)
			neighborneighbors = (*neighbor).m_node->getNeighbors();
			bool neighborneighborFound = false;
			for (std::list<RoutingEntry>::iterator neighborneighbor=neighborneighbors->begin(); neighborneighbor!=neighborneighbors->end() && !neighborneighborFound; neighborneighbor++) {
				if((*neighborneighbor).m_node == *node){
					neighborneighborFound = true;
				}
			}

			if (neighborneighborFound) {
				outputFile << "both";
			}
			else{
				outputFile << "forward";
			}

			outputFile << "];" << endl;
		}
	}

	// Limit the running time when generating the image
	outputFile << "maxiter=1000";
	// Make the edges a little longer so that you don't end upp with a knot of blackness...
	//outputFile << ", overlap=scale";
	outputFile << ";" << endl;

	// Write dot footer
	outputFile << "}" << endl;
}
